import axios from 'axios'
import {
  Message
} from 'element-ui'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000
})

const headerConfig = {}
export const initHeaderFunction = (value) => {
  Object.assign(headerConfig, value)
}

service.interceptors.request.use(
  config => {
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  response => {
    const res = response.data
    if (res.code !== 0) {
      if (res.code === -10004 || res.code === -1) {

      } else {
        Message({
          message: res.message || res.msg || 'Error',
          type: 'error',
          duration: 5 * 1000
        })
      }
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  error => {
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

// 输出方法
export const request = (url, data = {}, method = 'POST', otherHeader = {}) => {
  Object.assign(service.defaults.headers, otherHeader, headerConfig)
  return new Promise((resolve, reject) => {
    const options = {
      url,
      method
    }
    if (method.toLowerCase() === 'get') {
      options.params = data
    } else {
      options.data = data
    }
    service(options).then(res => {
      resolve(res)
    })
      .catch(error => {
        reject(error.data)
      })
  })
}
